// STL
#include <cmath>                    // std::exp(), ::sqrt(), ::log(), ::pow()
#include <stdexcept>                // std::runtime_error()


//
// DESC: Calculate the cumulative distribution function of the Kolmogorov--Smirnov distribution.
//
// -----
//
// NOTE: See "Numerical Recipes, 3rd Ed." Section 6.14.12.
//
inline double distribution::P_KS(
                                 const double z
                                 )
{
    if( z < 0. )
    {
        throw std::runtime_error("bad z in distribution::P_KS()");
    }

    if( z == 0. )
    {
        return 0.;
    }

    if( z < 1.18 )
    {
        double y = std::exp(-1.23370055013616983/(z*z));

        return ( 2.25675833419102515*std::sqrt(-std::log(y))*(y + std::pow(y,9) + std::pow(y,25) + std::pow(y,49)) );
    }
    else
    {
        double x = std::exp(-2*z*z);

        return ( 1. - 2*(x - std::pow(x,4) + std::pow(x,9)) );
    }
}
